from itsdangerous import TimedJSONWebSignatureSerializer as TJWSSeiralizer
from django.conf import settings

def generate_verify_url(user):
    serializer = TJWSSeiralizer(secret_key=settings.SECRET_KEY,
                                expires_in=300)
    data = {
        "user_id": user.id,
        "email": user.email
    }
    token = serializer.dumps(data)
    verify_url = "%s?token=%s" % (settings.EMAIL_VERIFY_URL,
                                  token.decode())
    return verify_url


def decode_token(token):
    #1,创建解密对象
    serializer = TJWSSeiralizer(secret_key=settings.SECRET_KEY, expires_in=300)

    #2,解密token
    try:
        data = serializer.loads(token)
        user_id = data.get("user_id")
        user = User.objects.get(id=user_id)
    except Exception as e:
        return None

    #3,返回响应
    return user